<template>
  <div style="margin: 15px;">
    <el-card  >
      <el-row :gutter="20">
        <el-col :span="7">
      <el-input placeholder="请输入查找的用户名" v-model="search" class="input-with-select">
      <el-button slot="append" icon="el-icon-search" v-on:click="user"></el-button>
      </el-input>
      </el-col>
      </el-row>
    </el-card>
    <el-card shadow="always" style="margin-top: 20px;">
      <el-button type="warning" icon="el-icon-edit" @click="showdialog">添加用户</el-button>
      <el-button type="primary" icon="el-icon-refresh-right" @click="renewdata()">刷新数据</el-button>
      <el-table
    :data="userdata"
    stripe
    style="width: 1000px;margin-top: 15px;">
    <el-table-column
      prop="name"
      label="姓名"
      width="140">
    </el-table-column>
    <el-table-column
      prop="telphone"
      label="联系电话"
      width="180">
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
      width="180">
    </el-table-column>
    <el-table-column
      prop="isadmin"
      label="是否管理员"
      width="180">
      <template slot-scope="scope">
        <el-tag
          :type="scope.row.isadmin === 0 ? 'primary' : 'success'"
          disable-transitions>{{scope.row.isadmin === 0?'否':'是'}}
        </el-tag>
        </template>
    </el-table-column>
    <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
            </el-table-column>
  </el-table>
  <el-pagination
      :total="total"
      :page-size="itemnum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 10, 12]"
      layout="total, sizes, prev, pager, next, jumper"
      background
      style="margin-top:20px;"
      >
    </el-pagination>
    </el-card>
<!-- 嵌套表单的对话框 -->
<el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="30%">
      <div style="margin-bottom:10px;">
        <el-alert
        title="您只能添加普通用户且无法修改用户级别"
        type="warning"
        show-icon
        >
        </el-alert>
      </div>
      <el-form :model="adduser" :label-width="labelwidth" ref="userdialog" :rules="rules">
        <el-form-item label="用户名" style="max-width:400px;"  
        prop="name">
          <el-input v-model="adduser.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" style="max-width:400px;"
        prop="telphone">
          <el-input v-model="adduser.telphone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系邮箱" style="max-width:400px;"
        prop="email">
          <el-input v-model="adduser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员" style="max-width:400px;">
          <el-switch
          v-model="adduser.isadmin"
          disabled>
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canceldialog">{{ this.type==='edit'?'取消':'重置' }}</el-button>
        <el-button type="primary" @click="addnewuser">{{ this.type==='edit'?'更新':'添加' }}</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
import { userdata, searchuser, setnewuser, updateuser } from '@/api/index'
import { mapMutations, mapState } from 'vuex'
import Cookie from 'js-cookie'
export default {
    name:'user',
    data(){
      var validatename = (rule, value, callback) => {
        if (value === '') callback(new Error('请输入用户名')); 
        else  callback()
      }
      var validatetelphone = (rule, value, callback) => {
        var numtype = /^[0-9]*$/
        if (value===''||!numtype.test(value)||value.length>=11)  
          return callback(new Error('请输入不超过10位的数字值,当前位数:'+value.length))
        else  callback()
      }
      var validateemail = (rule, value, callback) => {
        var emialrule = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
        if (value === ''||!emialrule.test(value)) callback(new Error('请输入正确的联系邮箱，格式如：xxx@163.com')); 
        else  callback()
      }
      return {
        search:'',
        total:0,
        itemnum:5,
        userdata:[],
        originallength:0,
        adduser:{
          id:'',
          name:'',
          telphone:'',
          email:'',
          isadmin:0
        },
        dialogTitle:'添加用户',
        labelwidth:'120px',
        // 对话框是否出现函数
        dialogFormVisible:false,
        //对话框表单验证规则
        rules:{
          name:[{ required: true, validator: validatename, trigger: 'blur' }],
          telphone:[{ type: 'number', required: true, validator: validatetelphone, trigger: 'blur' }],
          email:[{ required: true, validator: validateemail, trigger: ['blur', 'change'] }]
        }
      }
    },
    computed:{
      ...mapState('add',['userrowdata','type'])
    },
    methods:{
      ...mapMutations('add',['edituserrowdata','edittype']),
      //新增用户对话框函数
      showdialog(){
        if(this.type === 'edit'){
          this.adduser = { id:'',name:'',telphone:'',email:'',isadmin:0 },
          this.edittype(''),
          this.edituserrowdata([])
        }
        this.dialogTitle = '新增用户'
        this.dialogFormVisible = true
      },
      //对话框取消事件函数 
      canceldialog(){
        if(this.type === 'edit')  {this.edituserrowdata([]),this.edittype('')}
        //this.$refs.userdialog.resetFields();这个函数有点问题
        this.adduser = { id:'',name:'',telphone:'',email:'',isadmin:0 }
        this.dialogFormVisible = false
      },
      //对话框确定事件函数
      addnewuser(){
        this.$refs.userdialog.validate((valid) => {
          if (valid) {
            //新增模块
            if(this.type!=='edit') 
              setnewuser(this.adduser).then(req => {
                if(req.data.status===400)
                  this.$notify({
                    title: '警告',
                    message: req.data.msg,
                    type: 'warning',
                    duration: 2500
                  });
                else if(req.data.status===500)
                  this.$notify.error({
                    title: '错误',
                    message: req.data.msg,
                    duration: 2500
                  });
                else {
                  this.$notify({
                    title: '成功',
                    message: req.data.msg,
                    type: 'success',
                    duration: 2500
                  });
                  this.getuserdata()
                }
              }).catch(err => console.log(err))
            else 
              updateuser(this.adduser).then(req => {
                if(req.data.status===400)
                  this.$notify({
                    title: '警告',
                    message: req.data.msg,
                    type: 'warning',
                    duration: 2500
                  });
                else if(req.data.status===500)
                  this.$notify.error({
                    title: '错误',
                    message: req.data.msg,
                    duration: 2500
                  });
                else {
                  this.$notify({
                    title: '成功',
                    message: req.data.msg,
                    type: 'success',
                    duration: 2500
                  });
                  this.getuserdata()
                }
              }).catch(err => console.log(err))
            this.dialogFormVisible = false
          } else {
            this.$notify.error({
              title: '错误',
              message: '请按照表单验证规则输入数据！',
              duration: 2500
            });
            return false;
          }
        });
      },
      //搜索用户名函数
      user(){
        if(this.search===''){
          this.$notify({
            title: '警告',
            message: '请输入查找内容！',
            type: 'warning',
            duration: 2500
        })}else{
          searchuser({search:this.search}).then(res => {
            if(res.data.status===200){
              this.userdata = res.data.data
              this.$notify({
                title: '成功',
                message: '已为您找到该数据',
                type: 'success',
                duration: 2500
              });
              this.search = ''
            }else{
              this.$notify.error({
                title: '错误',
                message: '找不到数据，请核实输入！',
                duration: 2500
              });
            }
          }).catch(err => console.log(err))
        }
      },
      //编辑
      handleEdit(index,row){
        //说实话可以做外键连接..我试一试
        if(row.name!==Cookie.get('username')&&row.isadmin===1){
          this.$notify.error({
            title: '错误',
            message: '您无权修改其它管理员的数据',
            duration: 2500
          });
        }
        else{
        var rowdata = {
          id: row.id,
          name: row.name,
          telphone: row.telphone,
          email: row.email,
          isadmin: Boolean(row.isadmin) 
        }
        this.edittype('edit'),
        this.edituserrowdata(rowdata),
        this.dialogFormVisible = true,
        this.dialogTitle = '修改用户'
        this.adduser = this.userrowdata
      }
      },
      //假删
      handleDelete(index,row){
        if(row.isadmin===1){
          this.$notify.error({
            title: '错误',
            message: '您无权删除管理员的数据',
            duration: 2500
          });
        }
        else{
          this.$confirm('将永久删除该数据, 是否确定?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //假删
          this.userdata.splice(index,1)
          this.$message({
            type: 'success',
            message: '已删除'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
        }
      },
      handleCurrentChange(val){
        const va = (val-1)*this.itemnum
        //重新向数据库获取指定偏移量的数据
        this.getuserdata({offset:va,limit:this.itemnum})
      },
      //表单条数改变时传递条数信息
      handleSizeChange(val){
        this.itemnum = val
        this.getuserdata({limit:val})
      },
      //发送ajax请求获取用户数据
      getuserdata(config){
        userdata(config).then(res => {
          this.userdata = res.data.data
          this.total = res.data.total
          //数据值小于初始数据值时触发
          this.originallength = res.data.length
        }).catch(err => console.log(err))
      },
      renewdata(){
        this.$notify.info({
          title: '消息',
          message: '正在重新渲染数据请耐心等待'
        });
        setTimeout(() => {
          this.getuserdata()
          this.$notify({
          title: '成功',
          message: '渲染成功',
          type: 'success'
        });
        },2500);
      }
    },
    mounted(){
      this.getuserdata()
    }
}
</script>

<style>

</style>